package com.ld.collegetask;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ld.collegetask.beans.BaseJsonBean;
import com.ld.collegetask.beans.OrderBean;
import com.ld.collegetask.databinding.ActivityOrderMemberInfoBinding;
import com.ld.collegetask.serverInterface.RequestSerives;
import com.ld.collegetask.utils.AppApplication;
import com.ld.collegetask.utils.SharePreference;
import com.zaaach.toprightmenu.MenuItem;
import com.zaaach.toprightmenu.TopRightMenu;

import java.util.ArrayList;
import java.util.List;

import me.leefeng.promptlibrary.PromptDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class OrderMemberInfoActivity extends BaseActivity {
    private ActivityOrderMemberInfoBinding binding;

    private TopRightMenu order_member_info_complaint_menu;
    private PromptDialog promptDialog;
    private int orderId = 0;
    private int userId = 0;
    private OrderBean mOrder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_order_member_info);
        //设置标题
        setTitleView(this, binding.ilTitle, true, true, false, true);
        setLoadingView(this, binding.ilLoading);
        setTitle("任务详情");
        setIco(R.drawable.complaint);
        ico.setVisibility(View.INVISIBLE);

        orderId = getIntent().getIntExtra("orderId", 0);

        SharePreference sp = new SharePreference(getBaseContext());
        userId = sp.getUserId();

        loading_go();
        binding.orderMemberReleaseButton.setOnClickListener(this);
        promptDialog = new PromptDialog(this);

        LinearLayout.LayoutParams para1 = (LinearLayout.LayoutParams) binding.orderStatus1.getLayoutParams();
        para1.height = getResources().getDisplayMetrics().widthPixels / 6;
        binding.orderStatus1.setLayoutParams(para1);
    }

    @Override
    public void loading() {
        order_member_info();
    }

    /***
     * 获取订单基本信息
     * */
    private void order_member_info() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.order_member_info(orderId);
        call.enqueue(new Callback<String>() {

            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    OrderBean order = gson.fromJson(base.getJson(), OrderBean.class);
                    mOrder = order;
                    order.setUserId(userId);
                    binding.setOrderBean(order);
                    setIco(order);
                    loading_end();
                } else {
                    loading_error();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                loading_error();
            }
        });
    }

    /**
     * 设置ico图标显示或隐藏
     *
     * @param order
     */
    private void setIco(OrderBean order) {
        if (order.getOrderOstatus() == -2)
            ico.setVisibility(View.INVISIBLE);
        else if (order.getOrderOstatus() == -1)
            ico.setVisibility(View.VISIBLE);
        else if (order.getOrderOstatus() == 0)
            ico.setVisibility(View.VISIBLE);
        else if (order.getOrderOstatus() == 1)
            ico.setVisibility(View.VISIBLE);
        else if (order.getOrderOstatus() == 2)
            ico.setVisibility(View.VISIBLE);
        else if (order.getOrderOstatus() == 3)
            ico.setVisibility(View.VISIBLE);
        else if (order.getOrderOstatus() == 4)
            ico.setVisibility(View.INVISIBLE);
    }

    /***
     * 接单
     * haib.fan
     * */
    private void order_member_receive() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.order_member_receive(orderId, userId);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    promptDialog.dismiss();
                    Intent it = new Intent(OrderMemberInfoActivity.this, MainActivity.class);
                    setResult(2, it);
                    finish();
                    Log.e("CourseListBean", "点击了：接单成功");

                } else {
                    Log.e("CourseListBean", "点击了：接单失败");
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                promptDialog.dismiss();
            }
        });
    }

    /***
     * 接单完成
     * haib.fan
     * */
    private void order_member_complete() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.order_member_complete(orderId, userId);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    promptDialog.dismiss();
                    Intent it = new Intent(OrderMemberInfoActivity.this, MainActivity.class);
                    setResult(2, it);
                    finish();
                    Log.e("CourseListBean", "点击了：接单成功");

                } else {
                    Log.e("CourseListBean", "点击了：接单失败");
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                promptDialog.dismiss();
            }
        });
    }

    /***
     * 接单确认
     * haib.fan
     * */
    private void order_member_confirm() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.order_member_confirm(orderId, userId);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    promptDialog.dismiss();
                    Intent it = new Intent(OrderMemberInfoActivity.this, MainActivity.class);
                    setResult(2, it);
                    finish();
                    Log.e("CourseListBean", "点击了：接单成功");

                } else {
                    Log.e("CourseListBean", "点击了：接单失败");
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                promptDialog.dismiss();
            }
        });
    }

    private void complaint_member_save(String ccontent) {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.complaint_member_save(userId, orderId, ccontent);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    Toast.makeText(OrderMemberInfoActivity.this, "投诉成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(OrderMemberInfoActivity.this, "投诉失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    private void order_member_cancel(int flag) {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.order_member_cancel(orderId, userId, flag);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    Toast.makeText(OrderMemberInfoActivity.this, "取消订单成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(OrderMemberInfoActivity.this, "取消订单失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    private List<MenuItem> menuItems;

    private void showpopu() {
        order_member_info_complaint_menu = new TopRightMenu(OrderMemberInfoActivity.this);
        if (menuItems == null) {
            menuItems = new ArrayList<>();
        } else {
            menuItems.clear();
        }
        if (userId == mOrder.getUserUserId()) {                      //如果自己的用户id == 发任务的用户id，任务主
            if (mOrder.getOrderOstatus() >= 3 || mOrder.getOrderOstatus() <= -1) {
                ico.setVisibility(View.INVISIBLE);
            } else if (mOrder.getOrderOstatus() == 2) {
                menuItems.add(new MenuItem(0, "取消订单"));
                menuItems.add(new MenuItem(1, "投诉"));
            } else if (mOrder.getOrderOstatus() == 1) {
                menuItems.add(new MenuItem(0, "取消订单"));
            }
        } else if ((userId + "").equals(mOrder.getReceiveUserId())) {     //如果自己的用户id == 接单任务的用户id，接单主
            if (mOrder.getOrderOstatus() >= 3 || mOrder.getOrderOstatus() <= -1) {
                menuItems.add(new MenuItem(1, "投诉"));
            } else if (mOrder.getOrderOstatus() == 2) {
                menuItems.add(new MenuItem(0, "取消订单"));
                menuItems.add(new MenuItem(1, "投诉"));
            }
        } else {                                            //游客
            menuItems.add(new MenuItem(1, "投诉"));
        }
        order_member_info_complaint_menu
                .setWidth(260)
                .setHeight(LinearLayout.LayoutParams.WRAP_CONTENT)
                .showIcon(false)//显示菜单图标，默认为true
                .dimBackground(true)//背景变暗，默认为true
                .needAnimationStyle(true)//显示动画，默认为true
                .setAnimationStyle(R.style.TRM_ANIM_STYLE)//默认为R.style.TRM_ANIM_STYLE
                .addMenuList(menuItems)
                .setOnMenuItemClickListener(new TopRightMenu.OnMenuItemClickListener() {
                    @Override
                    public void onMenuItemClick(int position) {
                        if (menuItems.get(position).getIcon() == 0){
                            if (userId == binding.getOrderBean().getUserId()){
                                order_member_cancel(1);
                            }else {
                                order_member_cancel(2);
                            }
                        }else if (menuItems.get(position).getIcon() == 1) {
                            complaint_member_save("虚假订单");
                        }
                    }
                })
                .showAsDropDown(ico, -155, 0);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_head_ico:                  //感叹提示
                showpopu();
                break;
            case R.id.order_member_release_button:              //接单
                promptDialog.showLoading("正在提交");
                if (binding.getOrderBean().getOrderOstatus() == 1){
                    order_member_receive();
                }else if (binding.getOrderBean().getOrderOstatus() == 2){
                    order_member_complete();
                }else if (binding.getOrderBean().getOrderOstatus() == 3){
                    order_member_confirm();
                }
                break;
        }
    }
}
